<?php

namespace App\Middleware\Identity;

use App\Constants\ErrorCode;
use App\Constants\IdentityConstants;
use App\DataStore\RedisGeneral;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Ramsey\Uuid\Uuid;

class SrMiddleware  implements MiddlewareInterface
{
    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $userToken = $this->request->header('UTK');
        $userInfo = jsonDecode(RedisGeneral::getInc()->getUserKey('user:organ'.getOrganIdByOrganCode().":".$userToken));
        if(!empty($userInfo)){
            if(!($userInfo['user_type']&IdentityConstants::SR_USER)){
                return $this->response->json(
                    [
                        'data' => null,
                        'message' => ErrorCode::CODE_TYPE_ERROR_NOT_AUTH->getMessage(),
                        'code' => ErrorCode::CODE_TYPE_ERROR_NOT_AUTH,
                        'requestId' => Uuid::uuid4()->toString()
                    ]
                );
            }
        }else{
            return $this->response->json(
                [
                    'data' => null,
                    'message' => ErrorCode::CODE_TYPE_ERROR_LOGIN_EXPIRE->getMessage(),
                    'code' => ErrorCode::CODE_TYPE_ERROR_LOGIN_EXPIRE,
                    'requestId' => Uuid::uuid4()->toString()
                ]
            );
        }

        return $handler->handle($request);

    }
}